/*
 * TODO: Description
 *
 * Copyright (C) 2010 Johan Waldeback
 *  
 * This file is part of the OpenFMS project (http://www.openfms-project.org)
 * 
 * OpenFMS is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "BulletTickListener.h"
#include <cassert>

BulletTickListener::~BulletTickListener() {}
void BulletTickListener::onTick(const btDynamicsWorld *world, btScalar timeStep) {}
void BulletTickListener::onFrameStarted(const Ogre::FrameEvent &evt) {}



static void theCallback(btDynamicsWorld *world, btScalar timeStep)
{
	BulletTickListenerList *pHandler = static_cast<BulletTickListenerList *>(world->getWorldUserInfo());
	if( pHandler ) pHandler->onTick( world, timeStep );
}

BulletTickListenerList::BulletTickListenerList()
{
}

BulletTickListenerList::~BulletTickListenerList()
{
	destroy();
}

void BulletTickListenerList::destroy()
{
	removeAllListeners();
	detach();
}

void BulletTickListenerList::addListener(BulletTickListener *pListener)
{
	assert( pListener && "The pointer should point to something; not be NULL");
	m_listeners.push_back(pListener);
}

void BulletTickListenerList::removeAllListeners( bool freeItems )
{
	if( freeItems ) {
		for( ListType::iterator iter = m_listeners.begin(); iter != m_listeners.end(); ++ iter ) {
			delete *iter;
		}
	}
	m_listeners.clear();
}

void BulletTickListenerList::attach( btDynamicsWorld *world )
{
	world->setInternalTickCallback( theCallback, static_cast<void *>(this), true );
}

void BulletTickListenerList::detach()
{
	// TODO: chech that THIS instance is attached.
	/*if( m_pAttachedTo != NULL ) {
		m_pAttachedTo->setInternalTickCallback( NULL, NULL, true );
		m_pAttachedTo = NULL;
	}*/
}

void BulletTickListenerList::onTick(const btDynamicsWorld *world, btScalar timeStep)
{
	// todo: remove forces
	for( ListType::iterator iter = m_listeners.begin(); iter != m_listeners.end(); ++ iter )
	{
		(*iter)->onTick(world, timeStep);
	}
}

void BulletTickListenerList::onFrameStarted(const Ogre::FrameEvent &evt)
{
	// todo: remove forces
	for( ListType::iterator iter = m_listeners.begin(); iter != m_listeners.end(); ++ iter )
	{
		(*iter)->onFrameStarted(evt);
	}
}





